package com.ww.springboot.boot.thread.threadlocal;

import java.util.HashMap;
import java.util.Map;

/**
 * threadLocal 确保每个线程操作的对象都是独立的
 * 线程A的操作不影响线程B的结果
 *
 * threadLocal 只是一个壳子 真正存储数据的还是Thread里面的ThreadLocalMap
 * 线程消失 相应的ThreadLocalMap自然会被回收
 * 线程池中的线程可复用 所以不会被回收
 * ThreadLocal是Map中的key
 *
 * 设计成弱引用是为了在线程未回收 但是ThreadLocal引用被置为null时 ThreadLocal能够被回收掉
 * 是为了回收ThreadLocal 而不是ThreadLocalMap map除非线程被回收 否则是不会被垃圾回收的
 *
 * @author wanwei
 * @since 2021-04-06 18:18
 */
public class ThreadLocalDemo1 {

    private static final ThreadLocal<Map<String,String>> local = new ThreadLocal<>();
    private static int n = 0;

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> {
                Map<String,String> map = new HashMap<>();
                map.put("test",String.valueOf(finalI));
                local.set(map);
                map = local.get();
                System.out.println(map.get("test"));
            }).start();
        }
        Thread thread = null;
        for (int i = 0; i <= 10000; i++) {
            int finalI = i;
            thread = new Thread(() -> {
                n += finalI;
            });
            thread.start();
            thread.join();
        }
        System.out.println(n);
    }
}
